#include "GlobalHead.h"
#include "Command.h"
#include "Gui_Application.h"
#include "Action.h"
#include "MainWindow.h"



//===========================================================================
// Std_ShowObjects
//===========================================================================
DEF_STD_CMD_A(StdCmdShowObjects);

StdCmdShowObjects::StdCmdShowObjects()
: Command("Std_ShowObjects")
{
	sGroup        = QT_TR_NOOP("Standard-View");
	sMenuText     = QT_TR_NOOP("Show all objects");
	sToolTipText  = QT_TR_NOOP("Show all objects in the document");
	sStatusTip    = QT_TR_NOOP("Show all objects in the document");
	sWhatsThis    = "Std_ShowObjects";
	eType         = Alter3DView;
}

void StdCmdShowObjects::activated(int iMsg)
{
	// go through active document
// 	Gui::Document* doc = Application::Instance->activeDocument();
// 	App::Document* app = doc->getDocument();
// 	const std::vector<App::DocumentObject*> obj = app->getObjectsOfType
// 		(App::DocumentObject::getClassTypeId());
// 
// 	for (std::vector<App::DocumentObject*>::const_iterator it=obj.begin();it!=obj.end();++it) {
// 		doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=True"
// 			, app->getName(), (*it)->getNameInDocument());
// 	}
}

bool StdCmdShowObjects::isActive(void)
{
	//return App::GetApplication().getActiveDocument();
	return true;
}


// ---------------------------------------------------------- [3/2/2012 Administrator]



//===========================================================================
// Std_FreezeViews
//===========================================================================
class StdCmdFreezeViews : public Command
{
public:
	StdCmdFreezeViews();
	virtual ~StdCmdFreezeViews(){}
	const char* className() const
	{ return "StdCmdFreezeViews"; }

protected: 
	virtual void activated(int iMsg);
	virtual bool isActive(void);
	virtual Action * createAction(void);
	virtual void languageChange();

private:
	void onSaveViews();
	void onRestoreViews();

private:
	const int maxViews;
	int savedViews;
	int offset;
	QAction* saveView;
	QAction* freezeView;
	QAction* clearView;
	QAction* separator;
};

StdCmdFreezeViews::StdCmdFreezeViews()
: Command("Std_FreezeViews"), maxViews(50), savedViews(0)
{
	sGroup        = QT_TR_NOOP("Standard-View");
	sMenuText     = QT_TR_NOOP("Freeze display");
	sToolTipText  = QT_TR_NOOP("Freezes the current view position");
	sWhatsThis    = "Std_FreezeViews";
	sStatusTip    = QT_TR_NOOP("Freezes the current view position");
    sAccel        = "Shift+F";
	eType         = Alter3DView;
}

Action * StdCmdFreezeViews::createAction(void)
{
	ActionGroup* pcAction = new ActionGroup(this, getMainWindow());
	pcAction->setDropDownMenu(true);
	applyCommandData(pcAction);

	// add the action items
	saveView = pcAction->addAction(QObject::tr("Save views..."));
	pcAction->addAction(QObject::tr("Load views..."));
	pcAction->addAction(QString::fromAscii(""))->setSeparator(true);
	freezeView = pcAction->addAction(QObject::tr("Freeze view"));
	freezeView->setShortcut(QString::fromAscii(sAccel));
	clearView = pcAction->addAction(QObject::tr("Clear views"));
	separator = pcAction->addAction(QString::fromAscii(""));
	separator->setSeparator(true);
	offset = pcAction->actions().count();

	// allow up to 50 views
	for (int i=0; i<maxViews; i++)
		pcAction->addAction(QString::fromAscii(""))->setVisible(false);

	return pcAction;
}

void StdCmdFreezeViews::activated(int iMsg)
{
// 	ActionGroup* pcAction = qobject_cast<ActionGroup*>(_pcAction);
// 
// 	if (iMsg == 0) {
// 		onSaveViews();
// 	}
// 	else if (iMsg == 1) {
// 		onRestoreViews();
// 	}
// 	else if (iMsg == 3) {
// 		// Create a new view
// 		const char* ppReturn=0;
// 		getGuiApplication()->sendMsgToActiveView("GetCamera",&ppReturn);
// 
// 		QList<QAction*> acts = pcAction->actions();
// 		int index = 0;
// 		for (QList<QAction*>::ConstIterator it = acts.begin()+offset; it != acts.end(); ++it, index++) {
// 			if (!(*it)->isVisible()) {
// 				savedViews++;
// 				QString viewnr = QString(QObject::tr("Restore view &%1")).arg(index+1);
// 				(*it)->setText(viewnr);
// 				(*it)->setToolTip(QString::fromAscii(ppReturn));
// 				(*it)->setVisible(true);
// 				if (index < 9) {
// 					int accel = Qt::CTRL+Qt::Key_1;
// 					(*it)->setShortcut(accel+index);
// 				}
// 				break;
// 			}
// 		}
// 	}
// 	else if (iMsg == 4) {
// 		savedViews = 0;
// 		QList<QAction*> acts = pcAction->actions();   
// 		for (QList<QAction*>::ConstIterator it = acts.begin()+offset; it != acts.end(); ++it)
// 			(*it)->setVisible(false);
// 	}
// 	else if (iMsg >= offset) {
// 		// Activate a view
// 		QList<QAction*> acts = pcAction->actions();
// 		QString data = acts[iMsg]->toolTip();
// 		QString send = QString::fromAscii("SetCamera %1").arg(data);
// 		getGuiApplication()->sendMsgToActiveView(send.toAscii());
// 	}
}

void StdCmdFreezeViews::onSaveViews()
{
	// Save the views to an XML file
// 	QString fn = FileDialog::getSaveFileName(getMainWindow(), QObject::tr("Save frozen views"),
// 		QString(), QObject::tr("Frozen views (*.cam)"));
// 	if (fn.isEmpty())
// 		return;
// 	QFile file(fn);
// 	if (file.open(QFile::WriteOnly))
// 	{
// 		QTextStream str(&file);
// 		ActionGroup* pcAction = qobject_cast<ActionGroup*>(_pcAction);
// 		QList<QAction*> acts = pcAction->actions();      
// 		str << "<?xml version='1.0' encoding='utf-8'?>" << endl
// 			<< "<FrozenViews SchemaVersion=\"1\">" << endl;
// 		str << "  <Views Count=\"" << savedViews <<"\">" << endl;
// 
// 		for (QList<QAction*>::ConstIterator it = acts.begin()+offset; it != acts.end(); ++it) {
// 			if ( !(*it)->isVisible() )
// 				break;
// 			QString data = (*it)->toolTip();
// 
// 			// remove the first line because it's a comment like '#Inventor V2.1 ascii'
// 			QString viewPos;
// 			if ( !data.isEmpty() ) {
// 				QStringList lines = data.split(QString::fromAscii("\n"));
// 				if ( lines.size() > 1 ) {
// 					lines.pop_front();
// 					viewPos = lines.join(QString::fromAscii(" "));
// 				}
// 			}
// 
// 			str << "    <Camera settings=\"" << viewPos.toAscii().constData() << "\"/>" << endl;
// 		}
// 
// 		str << "  </Views>" << endl;
// 		str << "</FrozenViews>" << endl;
// 	}
}

void StdCmdFreezeViews::onRestoreViews()
{
// 	// Should we clear the already saved views
// 	if (savedViews > 0) {
// 		int ret = QMessageBox::question(getMainWindow(), QObject::tr("Restore views"), 
// 			QObject::tr("Importing the restored views would clear the already stored views.\n"
// 			"Do you want to continue?"), QMessageBox::Yes|QMessageBox::Default,
// 			QMessageBox::No|QMessageBox::Escape); 
// 		if (ret!=QMessageBox::Yes)
// 			return;
// 	}
// 
// 	// Restore the views from an XML file
// 	QString fn = FileDialog::getOpenFileName(getMainWindow(), QObject::tr("Restore frozen views"),
// 		QString(), QObject::tr("Frozen views (*.cam)"));
// 	if (fn.isEmpty())
// 		return;
// 	QFile file(fn);
// 	if (!file.open(QFile::ReadOnly)) {
// 		QMessageBox::critical(getMainWindow(), QObject::tr("Restore views"),
// 			QObject::tr("Cannot open file '%1'.").arg(fn));
// 		return;
// 	}
// 
// 	QDomDocument xmlDocument;
// 	QString errorStr;
// 	int errorLine;
// 	int errorColumn;
// 
// 	// evaluate the XML content
// 	if (!xmlDocument.setContent(&file, true, &errorStr, &errorLine, &errorColumn)) {
// 		std::cerr << "Parse error in XML content at line " << errorLine
// 			<< ", column " << errorColumn << ": "
// 			<< (const char*)errorStr.toAscii() << std::endl;
// 		return;
// 	}
// 
// 	// get the root element
// 	QDomElement root = xmlDocument.documentElement();
// 	if (root.tagName() != QLatin1String("FrozenViews")) {
// 		std::cerr << "Unexpected XML structure" << std::endl;
// 		return;
// 	}
// 
// 	bool ok;
// 	int scheme = root.attribute(QString::fromAscii("SchemaVersion")).toInt(&ok);
// 	if (!ok) return;
// 	// SchemeVersion "1"
// 	if (scheme == 1) {
// 		// read the views, ignore the attribute 'Count'
// 		QDomElement child = root.firstChildElement(QString::fromAscii("Views"));
// 		QDomElement views = child.firstChildElement(QString::fromAscii("Camera"));
// 		QStringList cameras;
// 		while (!views.isNull()) {
// 			QString setting = views.attribute(QString::fromAscii("settings"));
// 			cameras << setting;
// 			views = views.nextSiblingElement(QString::fromAscii("Camera"));
// 		}
// 
// 		// use this rather than the attribute 'Count' because it could be
// 		// changed from outside
// 		int ct = cameras.count();
// 		ActionGroup* pcAction = qobject_cast<ActionGroup*>(_pcAction);
// 		QList<QAction*> acts = pcAction->actions();      
// 
// 		int numRestoredViews = std::min<int>(ct, acts.size()-offset);
// 		savedViews = numRestoredViews;
// 
// 		if (numRestoredViews > 0)
// 			separator->setVisible(true);
// 		for(int i=0; i<numRestoredViews; i++) {
// 			QString setting = cameras[i];
// 			QString viewnr = QString(QObject::tr("Restore view &%1")).arg(i+1);
// 			acts[i+offset]->setText(viewnr);
// 			acts[i+offset]->setToolTip(setting);
// 			acts[i+offset]->setVisible(true);
// 			if ( i < 9 ) {
// 				int accel = Qt::CTRL+Qt::Key_1;
// 				acts[i+offset]->setShortcut(accel+i);
// 			}
// 		}
// 
// 		// if less views than actions
// 		for (int index = numRestoredViews+offset; index < acts.count(); index++)
// 			acts[index]->setVisible(false);
// 	}
}

bool StdCmdFreezeViews::isActive(void)
{
// 	View3DInventor* view = qobject_cast<View3DInventor*>(getMainWindow()->activeWindow());
// 	if (view) {
// 		saveView->setEnabled(savedViews > 0);
// 		freezeView->setEnabled(savedViews < maxViews);
// 		clearView->setEnabled(savedViews > 0);
// 		separator->setVisible(savedViews > 0);
// 		return true;
// 	}
// 	else {
// 		separator->setVisible(savedViews > 0);
// 	}

	return false;
}

//===========================================================================
// Std_ViewFitAll
//===========================================================================
DEF_STD_CMD_A(StdCmdViewFitAll);

StdCmdViewFitAll::StdCmdViewFitAll()
: Command("Std_ViewFitAll")
{
	sGroup        = QT_TR_NOOP("Standard-View");
	sMenuText     = QT_TR_NOOP("Fit all");
	sToolTipText  = QT_TR_NOOP("Fits the whole content on the screen");
	sWhatsThis    = "Std_ViewFitAll";
	sStatusTip    = QT_TR_NOOP("Fits the whole content on the screen");
	sPixmap       = "view-zoom-all";
	//iAccel        = 0;
	eType         = Alter3DView;
}

void StdCmdViewFitAll::activated(int iMsg)
{
	//doCommand(Command::Gui,"Gui.activeDocument().activeView().fitAll()");
	//doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewFit\")");
}

bool StdCmdViewFitAll::isActive(void)
{
	//return isViewOfType(Gui::View3DInventor::getClassTypeId());
	return getGuiApplication()->sendHasMsgToActiveView("ViewFit");
}

//===========================================================================
// Std_ViewFitSelection
//===========================================================================
DEF_STD_CMD_A(StdCmdViewFitSelection);

StdCmdViewFitSelection::StdCmdViewFitSelection()
: Command("Std_ViewFitSelection")
{
	sGroup        = QT_TR_NOOP("Standard-View");
	sMenuText     = QT_TR_NOOP("Fit selection");
	sToolTipText  = QT_TR_NOOP("Fits the selected content on the screen");
	sWhatsThis    = "Std_ViewFitSelection";
	sStatusTip    = QT_TR_NOOP("Fits the selected content on the screen");
#if QT_VERSION >= 0x040200
	sPixmap       = "view-zoom-selection";
#endif
	//iAccel        = 0;
	eType         = Alter3DView;
}

void StdCmdViewFitSelection::activated(int iMsg)
{
	//doCommand(Command::Gui,"Gui.activeDocument().activeView().fitAll()");
	//doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewSelection\")");
	doCommand((CommandStringFunction)Gui_Application::sendMsgToActiveView);
}

bool StdCmdViewFitSelection::isActive(void)
{
	//return isViewOfType(Gui::View3DInventor::getClassTypeId());
	return getGuiApplication()->sendHasMsgToActiveView("ViewSelection");
}




void StdCmdFreezeViews::languageChange()
{
// 	Command::languageChange();
// 
// 	if (!_pcAction)
// 		return;
// 	ActionGroup* pcAction = qobject_cast<ActionGroup*>(_pcAction);
// 	QList<QAction*> acts = pcAction->actions();
// 	acts[0]->setText(QObject::tr("Save views..."));
// 	acts[1]->setText(QObject::tr("Load views..."));
// 	acts[3]->setText(QObject::tr("Freeze view"));
// 	acts[4]->setText(QObject::tr("Clear views"));
// 	int index=1;
// 	for (QList<QAction*>::ConstIterator it = acts.begin()+5; it != acts.end(); ++it, index++) {
// 		if ((*it)->isVisible()) {
// 			QString viewnr = QString(QObject::tr("Restore view &%1")).arg(index);
// 			(*it)->setText(viewnr);
// 		}
// 	}
}


// --------------------------------------------------------------- [3/2/2012 Administrator]

void CreateViewStdCommands(void)
{
	CommandManager &rcCmdMgr = Gui_Application::instance->commandManager();
	rcCmdMgr.addCommand(new StdCmdShowObjects());
   rcCmdMgr.addCommand(new StdCmdFreezeViews());
   rcCmdMgr.addCommand(new StdCmdViewFitAll());
   rcCmdMgr.addCommand(new StdCmdViewFitSelection());
}